const urlLib = require('url');
const http = require('http');
const https = require('https');
const pathLib = require('path');
const fs = require('fs');

let url = 'http://www.baidu.com'

let request = http.request(url, response => {
    const { statusCode } = response
    if (
        (statusCode >= 200 && statusCode < 300) || 
        statusCode === 304
    ) {
        let arr = []
        response.on('data', data => arr.push(data))
        response.on('end', () => {
            let buffer = Buffer.concat(arr)
            fs.writeFile(pathLib.resolve('tmp', 'baidu.html'), buffer, err => {
                if (err) {
                    console.log('写入文件失败', err)
                } else {
                    console.log('文件写入成功')
                }
            })
        })
        console.log('ok')
    } else if (statusCode === 301 || statusCode === 302) {
        console.log(response.headers)
    } else {
        console.log('fail', statusCode)
    }
})

request.on('error', error => {
    console.log('fail', error)
})

request.write('')

request.end()
